package dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

import bean.Producer;
import database.PersistenceUtil;

public class ProducerDao {
	private static final Logger LOGGER = Logger.getLogger(ProducerDao.class);
	
	public static Producer findProducer(String name) throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			List<Producer> producers = conn.createNamedQuery("Producer.findbyName", Producer.class).setParameter("producer", name).getResultList();
			if (producers.isEmpty()) {
				return null;
			}
			return producers.get(0);
		}  catch (Exception e) {
			LOGGER.error("Error while getting producer with name "+ name +" \n" + e.getMessage());
			throw e;
		} finally{
			conn.close();
		}
	}
	
	public static Producer findProducerById(Long id) throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			List<Producer> producers = conn.createNamedQuery("Producer.findbyID", Producer.class).setParameter("id", id).getResultList();
			if (producers.isEmpty()) {
				return null;
			}
			return producers.get(0);
		}  catch (Exception e) {
			LOGGER.error("Error while getting producer with id "+ id +" \n" + e.getMessage());
			throw e;
		} finally{
			conn.close();
		}
	}
	
	public static List<Producer> getProducers() throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			List<Producer> producers = conn.createNamedQuery("Producer.findAll", Producer.class).getResultList();
			if (producers.isEmpty()) {
				return null;
			}
			return producers;
		} catch (Exception e) {
			LOGGER.error("Error while getting producers \n" + e.getMessage());
			throw e;
		} finally{
				conn.close();
		}
	}
}
